<template>
  <a-card :body-style="{padding: '24px 0px'}" :bordered="false">
    <a-form @submit="handleSubmit" :form="form">
      <a-row>
        <a-col :span="17" style="padding-right:15px;padding-left:15px;">
          <a-form-item
            label="包名"
            :labelCol="{lg: {span: 3}, sm: {span: 3}}"
            :wrapperCol="{lg: {span: 14}, sm: {span: 21} }">
            <a-input
              :disabled="disabled"
              v-decorator="[
                'packageName',
                {rules: [{ required: true, message: '请输入包名' }]}
              ]"
              name="packageName"
              placeholder="请输入包名" />
          </a-form-item>
          <a-form-item
            label="包地址"
            :labelCol="{lg: {span: 3}, sm: {span: 3}}"
            :wrapperCol="{lg: {span: 14}, sm: {span: 21} }">
            <a-input
              :disabled="disabled"
              v-decorator="[
                'packageUrl',
                {rules: [{ required: true, message: '请输入包地址' }]}
              ]"
              name="packageUrl"
              placeholder="请输入包地址" />
          </a-form-item>
          <a-form-item
            label="应用名称"
            :labelCol="{lg: {span: 3}, sm: {span: 3}}"
            :wrapperCol="{lg: {span: 14}, sm: {span: 21} }">
            <a-input
              :disabled="disabled"
              v-decorator="[
                'name',
                {rules: [{ required: true, message: '请输入应用名称' },{max:20, message: '应用名称最多20个字符' }]}
              ]"
              name="name"
              placeholder="请输入应用名称" />
          </a-form-item>
          <a-form-item
            label="APP版本"
            :labelCol="{lg: {span: 3}, sm: {span: 3}}"
            :wrapperCol="{lg: {span: 14}, sm: {span: 21} }">
            <a-input
              :disabled="disabled"
              v-decorator="[
                'version',
                {rules: [{ required: true, message: '请输入APP版本' }]}
              ]"
              name="version"
              placeholder="请输入APP版本" />
          </a-form-item>
          <a-form-item
            label="评分"
            :labelCol="{lg: {span: 3}, sm: {span: 3}}"
            :wrapperCol="{lg: {span: 14}, sm: {span: 21} }">
            <a-input
              :disabled="disabled"
              v-decorator="[
                'scope',
                {rules: [{ required: true, message: '请输入评分' }]}
              ]"
              name="scope"
              placeholder="请输入评分" />
          </a-form-item>
          <a-form-item
            label="开发商"
            :labelCol="{lg: {span: 3}, sm: {span: 3}}"
            :wrapperCol="{lg: {span: 14}, sm: {span: 21} }">
            <a-input
              :disabled="disabled"
              v-decorator="[
                'developerName',
                {rules: [{ required: true, message: '请输入开发商名称' }]}
              ]"
              name="developerName"
              placeholder="请输入开发商名称" />
          </a-form-item>
          <a-form-item
            label="类型"
            :labelCol="{lg: {span: 3}, sm: {span: 3}}"
            :wrapperCol="{lg: {span: 14}, sm: {span: 21} }"
          >
            <div
              v-decorator="[
                'appTypeId',
                {rules: [{ required: true, message: '请选择类型' }]}
              ]"
              name="appTypeId">
              <a-select :disabled="disabled" :value="option1Val" style="width: 120px;margin-right:10px" placeholder="一级分类" @change="changeSelect1Click">
                <a-select-option :value="String(item.id)" v-for="(item,index) in option1List" :key="index">{{ item.name }}</a-select-option>
              </a-select>
              <a-select :disabled="disabled" :value="option2Val" style="width: 120px;margin-right:10px" placeholder="二级分类" @change="changeSelect2Click">
                <a-select-option :value="String(item.id)" v-for="(item,index) in option2List" :key="index">{{ item.name }}</a-select-option>
              </a-select>
              <a-select :disabled="disabled" :value="option3Val" style="width: 120px" placeholder="三级分类" @change="changeSelect3Click">
                <a-select-option :value="String(item.id)" v-for="(item,index) in option3List" :key="index">{{ item.name }}</a-select-option>
              </a-select>
            </div>
          </a-form-item>
          <a-form-item
            label="标签"
            :labelCol="{lg: {span: 3}, sm: {span: 3}}"
            :wrapperCol="{lg: {span: 14}, sm: {span: 21} }">
            <a-input
              :disabled="disabled"
              v-decorator="[
                'tag',
                {rules: [{ required: true, message: '请输入标签' }, {validator: validatorTag}]}
              ]"
              name="tag"
              placeholder="最多4个标签，多个标签用英文逗号隔开" />
          </a-form-item>
          <a-form-item
            label="应用介绍"
            :labelCol="{lg: {span: 3}, sm: {span: 3}}"
            :wrapperCol="{lg: {span: 14}, sm: {span: 21} }">
            <a-textarea
              :disabled="disabled"
              rows="4"
              placeholder="请输入介绍内容"
              v-decorator="[
                'introduction',
                {rules: [{ required: true, message: '请输入应用介绍内容' }]}
              ]" />
          </a-form-item>
          <a-form-item
            label="版权证明">
            <upload-image
              :disabled="disabled"
              :imageUrl="copyrightPic"
              :imageType="2"
              :intoType="2"
              @uploadImage="uploadImage"
              v-decorator="[
                'copyrightPic',
                {
                  rules: [{ required: true, message: '请上传图片' }],
                },
              ]"
            ></upload-image>
          </a-form-item>
          <a-form-item
            label="资质证明">
            <upload-image
              :disabled="disabled"
              :imageUrl="qualificationDoc"
              :imageType="2"
              :intoType="3"
              @uploadImage="uploadImage"
              v-decorator="[
                'qualificationDoc',
                {
                  rules: [{ required: true, message: '请上传图片' }],
                },
              ]"
            ></upload-image>
          </a-form-item>
          <a-form-item
            label="应用截图">
            <upload-image
              :disabled="disabled"
              :imageUrl="appPics"
              :imageType="2"
              :intoType="4"
              @uploadImage="uploadImage"
              v-decorator="[
                'appPics',
                {
                  rules: [{ required: true, message: '请上传图片' }],
                },
              ]"
            ></upload-image>
          </a-form-item>
        </a-col>
        <a-col :span="7" style="text-align:left">
          <div style="max-width:80%;min-width:200px">
            <a-form-item
              label="应用图标">
              <upload-image
                :disabled="disabled"
                :imageUrl="iconUrl"
                :imageType="2"
                :intoType="1"
                @uploadImage="uploadImage"
                v-decorator="[
                  'iconUrl',
                  {
                    rules: [{ required: true, message: '请上传图片' }],
                  },
                ]"
              ></upload-image>
            </a-form-item>
          </div>
        </a-col>
      </a-row>
      <a-form-item
        :wrapperCol="{ span: 24 }"
        style="text-align: center"
        class="form_btn">
        <a-button :disabled="disabled" :loading="confirmLoading" htmlType="submit" type="primary">提交</a-button>
        <a-button style="margin-left: 8px" @click="backClick">返回</a-button>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script>
import UploadImage from '@/viewsVue/commit/UploadImage'
import { mapActions } from 'vuex'
export default {
  name: 'ChildForm',
  data () {
    return {
      disabled: false,
      item: {},
      option1Val: undefined,
      option1List: [
        { name: '软件', id: 1 },
        { name: '游戏', id: 2 }
      ],
      option2Val: undefined,
      option2List: [],
      option3Val: undefined,
      option3List: [],
      iconUrl: '',
      copyrightPic: '',
      qualificationDoc: '',
      appPics: [],
      // form
      form: this.$form.createForm(this),
      confirmLoading: false
    }
  },
  mounted () {
    if (this.$route.meta.seen) {
      this.disabled = true
    } else {
      this.disabled = false
    }
    if (this.$route.params.id) {
      this.Apidetail(this.$route.params.id)
    }
  },
  components: {
    UploadImage
  },
  methods: {
    ...mapActions(['GetInto', 'ManageList', 'IntoAdd', 'IntoEdit']),
    backClick () {
      this.$router.go(-1)
    },
    uploadImage (val) { // 图片上传成功显示
      if (val.type === 1) {
        this.iconUrl = val.img
      } else if (val.type === 2) {
        this.copyrightPic = val
      } else if (val.type === 3) {
        this.qualificationDoc = val
      } else if (val.type === 4) {
        this.appPics = val.img
        this.$nextTick(() => {
          this.form.setFieldsValue({ 'appPics': val.img })
        })
      }
    },
    changeSelect1Click (val) { // 一级分类
      this.form.setFieldsValue({ 'appTypeId': val })
      this.option2List = []
      this.option3List = []
      this.option2Val = ''
      this.option3Val = ''
      this.ManageList({
        keyword: '',
        enabled: '',
        parentId: val,
        page: 1,
        pageSize: 10000
      })
        .then((res) => this.TypeSuccess(res, 2))
        .catch(err => this.requestFailed(err))
    },
    changeSelect2Click (val) { // 二级分类
      this.form.setFieldsValue({ 'appTypeId': val })
      this.option3List = []
      this.option3Val = ''
      this.ManageList({
        keyword: '',
        enabled: '',
        parentId: val,
        page: 1,
        pageSize: 10000
      })
        .then((res) => this.TypeSuccess(res, 3))
        .catch(err => this.requestFailed(err))
    },
    changeSelect3Click (val) {
      this.form.setFieldsValue({ 'appTypeId': val })
    },
    Apidetail (Id) {
      const {
        GetInto
      } = this
      GetInto({ id: Id })
        .then((res) => this.DetailSuccess(res))
        .catch(err => this.requestFailed(err))
    },
    DetailSuccess (res) {
      if (res.status === 200 || res.status === '200') {
        this.item = res.data
        if (res.data.iconUrl) {
          this.iconUrl = res.data.iconUrl
        }
        if (res.data.copyrightPic) {
          this.copyrightPic = res.data.copyrightPic
        }
        if (res.data.qualificationDoc) {
          this.qualificationDoc = res.data.qualificationDoc
        }
        if (res.data.appPics) {
          this.appPics = res.data.appPics
        }
        this.form = this.$form.createForm(this, {
          mapPropsToFields: () => {
            return {
              packageName: this.$form.createFormField({
                value: res.data.packageName || ''
              }),
              packageUrl: this.$form.createFormField({
                value: res.data.packageUrl || ''
              }),
              name: this.$form.createFormField({
                value: res.data.name || ''
              }),
              version: this.$form.createFormField({
                value: res.data.version || ''
              }),
              scope: this.$form.createFormField({
                value: res.data.scope || ''
              }),
              developerName: this.$form.createFormField({
                value: res.data.developerName || ''
              }),
              tag: this.$form.createFormField({
                value: JSON.parse(res.data.tag).join(',') || ''
              }),
              introduction: this.$form.createFormField({
                value: res.data.introduction || ''
              }),
              iconUrl: this.$form.createFormField({
                value: res.data.iconUrl || ''
              }),
              copyrightPic: this.$form.createFormField({
                value: res.data.copyrightPic || ''
              }),
              qualificationDoc: this.$form.createFormField({
                value: res.data.qualificationDoc || ''
              }),
              appPics: this.$form.createFormField({
                value: res.data.appPics || ''
              })
            }
          }
        })
        var arr = []; var typePath = []
        if (res.data.appTypePath) {
          typePath = res.data.appTypePath.split('/')
          for (var i in typePath) {
            if (typePath[i]) {
              arr.push(typePath[i])
            }
          }
        }
        var data = {
          keyword: '',
          enabled: '',
          parentId: '',
          page: 1,
          pageSize: 10000
        }

        if (arr.length !== 0) {
          this.option1Val = arr[0]
          var appTypeId = ''
          if (arr.length === 1) {
            appTypeId = arr[0]
          } else if (arr.length === 2) {
            appTypeId = arr[1]
          } else if (arr.length === 3) {
            appTypeId = arr[2]
          }
          this.$nextTick(() => {
            this.form.setFieldsValue({ 'appTypeId': appTypeId })
          })
        }
        if (arr.length >= 2) {
          this.option2Val = arr[1]
          data.parentId = arr[0]
          this.ManageList(data)
            .then((res) => this.TypeSuccess(res, 2))
            .catch(err => this.requestFailed(err))
        }
        if (arr.length >= 3) {
          this.option3Val = arr[2]
          data.parentId = arr[1]
          this.ManageList(data)
            .then((res) => this.TypeSuccess(res, 3))
            .catch(err => this.requestFailed(err))
        }
      } else {
        this.requestFailed(res)
      }
    },
    TypeSuccess (res, index) {
      if (res.status === 200 || res.status === '200') {
        if (res.data.list && res.data.list.length !== 0) {
          if (index === 2) {
            this.option2List = res.data.list
          } else if (index === 3) {
            this.option3List = res.data.list
          }
        } else {
          if (index === 2) {
            this.option2List = []
          } else if (index === 3) {
            this.option3List = []
          }
        }
      } else {
        this.requestFailed(res)
      }
    },
    // 自定义验证
    validatorTag (rule, value, callback) {
      var arr = value.split(',')
      for (var i in arr) {
        if (arr[i].length >= 9) {
          // eslint-disable-next-line standard/no-callback-literal
          callback('每个标签最多8个字符')
        }
        if (arr.length >= 5) {
        // eslint-disable-next-line standard/no-callback-literal
          callback('标签最多4个')
        }
      }
      callback()
    },
    // handler
    handleSubmit (e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true
          if (this.$route.params.id) {
            values.id = this.$route.params.id
            this.IntoEdit(values)
              .then((res) => this.submitSuccess(res))
              .catch(err => this.requestFailed(err))
          } else {
            this.IntoAdd(values)
              .then((res) => this.submitSuccess(res))
              .catch(err => this.requestFailed(err))
          }
        }
      })
    },
    submitSuccess (res) {
      if (res.status === 200 || res.status === '200') {
        this.$notification['success']({
          message: '成功',
          description: res.message,
          duration: 4
        })
        setTimeout(() => {
          this.confirmLoading = false
        }, 1500)
      } else {
        this.requestFailed(res)
      }
    },
    requestFailed (err) {
      this.$notification['error']({
        message: '错误',
        description: err.message || '请求出现错误，请稍后再试',
        duration: 4
      })
      setTimeout(() => {
        this.confirmLoading = false
      }, 1500)
    }
  }
}
</script>
